/*
 * cstb16s.c
 *
 *  Created on: May 24, 2021
 *      Author: Admin
 */
#include "cst816s.h"
#include "dev_gpio.h"
#include "dev_i2c.h"


#define I2C_CST816S_ADDR		0x2A
extern I2C_HandleTypeDef hi2c1;


void touch_init(void) {
	MX_I2C1_Init();
	Dev_Gpio_Init();
	//触摸复位
	HAL_GPIO_WritePin(GPIOB, GPIO_PIN_0, GPIO_PIN_RESET);
	HAL_Delay(1);
	HAL_GPIO_WritePin(GPIOB, GPIO_PIN_0, GPIO_PIN_SET);
}

int read_touch_data(struct ts_event *data)
{
	u8 buf[POINT_READ_BUF] = { 0 };
	u16 reg = 0;
	int ret = -1;
	int i = 0;
	u8 pointid = HYN_MAX_ID;


	//ret = hyn_i2c_read(hyn_i2c_client, buf, 1, buf, POINT_READ_BUF);
	ret = HAL_I2C_Mem_Read(&hi2c1, I2C_CST816S_ADDR, reg, I2C_MEMADD_SIZE_8BIT, buf, POINT_READ_BUF, 10);

	if (ret != 0)
	{
		printf("Read touchdata failed, ret: %d\n", ret);
		return ret;
	}

	if((buf[HYN_TOUCH_EVENT_POS] >> 6) == 0) { //无触摸事件返回
		return -1;
	}
	//printf("buf[1]: %d\n", buf[1]);	//滑动
	
	memset(data, 0, sizeof(struct ts_event));
	data->touch_point_num = buf[FT_TOUCH_POINT_NUM] & 0x0F;
	data->touch_point = 0;
	
	//滑动动作
	data->touchs = buf[HYN_FACE_DETECT_POS];
	
	//for (i = 0; i < tpd_dts_data.touch_max_num; i++)
	for (i = 0; i < 1; i++)
	{
		pointid = (buf[HYN_TOUCH_ID_POS + HYN_TOUCH_STEP * i]) >> 4;
		if (pointid >= HYN_MAX_ID)
			break;
		else
			data->touch_point++;
		data->au16_x[i] =
			(s16) (buf[HYN_TOUCH_X_H_POS + HYN_TOUCH_STEP * i] & 0x0F) <<
			8 | (s16) buf[HYN_TOUCH_X_L_POS + HYN_TOUCH_STEP * i];
		data->au16_y[i] =
			(s16) (buf[HYN_TOUCH_Y_H_POS + HYN_TOUCH_STEP * i] & 0x0F) <<
			8 | (s16) buf[HYN_TOUCH_Y_L_POS + HYN_TOUCH_STEP * i];
		data->au8_touch_event[i] =
			buf[HYN_TOUCH_EVENT_POS + HYN_TOUCH_STEP * i] >> 6;
//		data->au8_finger_id[i] =
//			(buf[HYN_TOUCH_ID_POS + HYN_TOUCH_STEP * i]) >> 4;

//		data->pressure[i] =
//			(buf[HYN_TOUCH_XY_POS + HYN_TOUCH_STEP * i]);//cannot constant value
//		data->area[i] =
//			(buf[HYN_TOUCH_MISC + HYN_TOUCH_STEP * i]) >> 4;
		if ((data->au8_touch_event[i]==0 || data->au8_touch_event[i]==2)&&(data->touch_point_num==0))
			break;
	}

	//printf("x:%d, y:%d, event:%d\n",data->au16_x[0],data->au16_y[0],data->au8_touch_event[0]);
	return 0;
}




